package logic

import (
	"context"
	"errors"
	"shop-switcher/models/cache"
	"shop-switcher/models/mysql"
	"shop-switcher/pkg"
	"shop-switcher/shoprpc/internal/svc"
	"shop-switcher/shoprpc/shoprpc"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *shoprpc.LoginRequest) (*shoprpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	result, _ := cache.Rdb.Get(l.ctx, "sendsms"+in.Mobile).Result()
	if result != in.Sendsms {
		return nil, errors.New("短信验证码错误")
	}
	s, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Mobile).Result()
	if s != in.Captcha {
		return nil, errors.New("图形验证码错误")
	}
	user := mysql.User{
		Model:    gorm.Model{},
		Mobile:   in.Mobile,
		Password: pkg.Md5(in.Password),
	}
	if err := user.FindUser(mysql.DB, in.Mobile); err != nil {
		return nil, err
	}
	if user.Password != pkg.Md5(in.Password) {
		return nil, errors.New("密码错误")
	}

	return &shoprpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
